import torch
import torchvision
import torchvision.transforms as transforms
from sklearn import svm
from sklearn.metrics import accuracy_score

# 数据加载和预处理
transform = transforms.Compose([
    transforms.ToTensor(),  # 将图像转换为Tensor
    transforms.Normalize((0.1307,), (0.3081,))  # 归一化处理
])

# 加载训练集
trainset = torchvision.datasets.MNIST(root='./data/mnist', train=True,
                                      download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=len(trainset),
                                          shuffle=True)

# 加载测试集
testset = torchvision.datasets.MNIST(root='./data/mnist', train=False,
                                     download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=len(testset),
                                         shuffle=False)

# 获取训练数据和标签
train_images, train_labels = next(iter(trainloader))
train_images = train_images.view(train_images.size(0), -1).numpy()
train_labels = train_labels.numpy()

# 获取测试数据和标签
test_images, test_labels = next(iter(testloader))
test_images = test_images.view(test_images.size(0), -1).numpy()
test_labels = test_labels.numpy()

# 创建SVM模型
clf = svm.SVC(kernel='linear')

# 训练模型
clf.fit(train_images, train_labels)

# 预测测试集
predictions = clf.predict(test_images)

# 计算准确率
accuracy = accuracy_score(test_labels, predictions)
print(f"Accuracy: {accuracy * 100:.2f}%")
